package com.jquest.io;

import com.jquest.misc.Tileset;
import com.jquest.misc.JarResources;

import java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.HashMap;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;

import org.newdawn.slick.Image;
import org.newdawn.slick.opengl.ImageData;

/**
 * Created by IntelliJ IDEA.
 * User: Johan
 * Date: 2009-dec-13
 * Time: 01:23:01
 * To change this template use File | Settings | File Templates.
 */
public class TilesetLoader {


    private Tileset tileset;

    public TilesetLoader() {

    }

    private void loadFiles(String file) {
        try {
            JarResources jar = new JarResources(file);
            StringBuilder sb = new StringBuilder();
            ByteArrayInputStream bais = new ByteArrayInputStream(jar.getResource("data.txt"));
            int c;
            while((c = bais.read()) != -1) {
                sb.append((char) c);
            }
            parseInfo(sb, jar);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public Tileset load(String file) {
        tileset = new Tileset();
        loadFiles(file);
        return tileset;
    }

    private void parseInfo(StringBuilder sb, JarResources jar) throws Exception {
        String[] lines = sb.toString().split("\n");
        System.out.println(lines[0]);
        tileset.setName(lines[0]);
        tileset.setFileName(jar.getFileName());
        
        for(int i = 1; i < lines.length; i++) {
            String[] columns = lines[i].split(",");
            String fileName = columns[0];
            String displayName = columns[1].trim();

            Enumeration e = jar.getContent().keys();
            while(e.hasMoreElements()) {
                String name = (String) e.nextElement();
                if(name.equalsIgnoreCase(fileName)) {
                    ByteArrayInputStream image = new ByteArrayInputStream(jar.getResource(name));
                    Image img = new Image(image, displayName, false);
                    img.setName(displayName); //Due to a bug in the library i have to set displayName again
                    tileset.add(displayName, img);
                }
            }
        }
    }

}
